/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security.multi;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import com.zhg2yqq.wheels.security.ISecurityEventHook;

/**
 * @author zhg2yqq, 2023年3月16日
 * @version zhg2yqq v1.0
 */
public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";
    public static final String SPRING_SECURITY_FORM_PHONE_KEY = "phone";
    public static final String SPRING_SECURITY_FORM_EMAIL_KEY = "email";
    public static final String SPRING_SECURITY_FORM_CODE_KEY = "code";
    public static final String SPRING_SECURITY_FORM_KEY_KEY = "key";
    public static final String SPRING_SECURITY_FORM_TYPE_KEY = "type";

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher(
            "/login", "POST");

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;
    private String phoneParameter = SPRING_SECURITY_FORM_PHONE_KEY;
    private String emailParameter = SPRING_SECURITY_FORM_EMAIL_KEY;
    private String codeParameter = SPRING_SECURITY_FORM_CODE_KEY;
    private String keyParameter = SPRING_SECURITY_FORM_KEY_KEY;
    private String typeParameter = SPRING_SECURITY_FORM_TYPE_KEY;
    private AuthenticationTokenProducer tokenProducer;
    private ISecurityEventHook securityEventHook;

    private boolean postOnly = true;

    public CustomAuthenticationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
        this.tokenProducer = new AuthenticationTokenProducer();
    }

    public CustomAuthenticationFilter(AuthenticationTokenProducer tokenProducer) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
        this.tokenProducer = tokenProducer;
    }

    public CustomAuthenticationFilter(AuthenticationTokenProducer tokenProducer,
                                      AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
        this.tokenProducer = tokenProducer;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response)
            throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        CustomAuthenticationToken authRequest = buildToken(request);
        setDetails(request, authRequest);
        try {
            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (AuthenticationException ex) {
            if (this.securityEventHook != null) {
                securityEventHook.catchAuthenticationException(ex, request, response);
            }
            throw ex;
        }
    }

    public CustomAuthenticationToken buildToken(HttpServletRequest request) {
        String type = obtainType(request);
        AuthenticationTokenParameter parameter = new AuthenticationTokenParameter().setType(type)
                .setUsername(obtainUsername(request)).setPassword(obtainPassword(request))
                .setEmail(obtainEmail(request)).setPhone(obtainPhone(request))
                .setKey(obtainKey(request)).setCode(obtainCode(request));
        return tokenProducer.create(type, parameter);
    }

    @Nullable
    protected String obtainPassword(HttpServletRequest request) {
        return request.getParameter(this.passwordParameter);
    }

    @Nullable
    protected String obtainUsername(HttpServletRequest request) {
        return request.getParameter(this.usernameParameter);
    }

    @Nullable
    protected String obtainPhone(HttpServletRequest request) {
        return request.getParameter(this.phoneParameter);
    }

    @Nullable
    protected String obtainEmail(HttpServletRequest request) {
        return request.getParameter(this.emailParameter);
    }

    @Nullable
    protected String obtainKey(HttpServletRequest request) {
        return request.getParameter(this.keyParameter);
    }

    @Nullable
    protected String obtainCode(HttpServletRequest request) {
        return request.getParameter(this.codeParameter);
    }

    @Nullable
    protected String obtainType(HttpServletRequest request) {
        return request.getParameter(this.typeParameter);
    }

    protected void setDetails(HttpServletRequest request, AbstractAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    public void setUsernameParameter(String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    public void setPasswordParameter(String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }

    public void setPhoneParameter(String phoneParameter) {
        Assert.hasText(phoneParameter, "Phone parameter must not be empty or null");
        this.phoneParameter = phoneParameter;
    }

    public void setEmailParameter(String emailParameter) {
        Assert.hasText(emailParameter, "Email parameter must not be empty or null");
        this.emailParameter = emailParameter;
    }

    public void setCodeParameter(String codeParameter) {
        Assert.hasText(codeParameter, "Code parameter must not be empty or null");
        this.codeParameter = codeParameter;
    }

    public void setKeyParameter(String keyParameter) {
        Assert.hasText(keyParameter, "Key parameter must not be empty or null");
        this.keyParameter = keyParameter;
    }

    public void setTypeParameter(String typeParameter) {
        Assert.hasText(typeParameter, "Type parameter must not be empty or null");
        this.typeParameter = typeParameter;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public final String getUsernameParameter() {
        return this.usernameParameter;
    }

    public final String getPasswordParameter() {
        return this.passwordParameter;
    }

    public String getPhoneParameter() {
        return this.phoneParameter;
    }

    public String getEmailParameter() {
        return this.emailParameter;
    }

    public String getCodeParameter() {
        return this.codeParameter;
    }

    public String getKeyParameter() {
        return this.keyParameter;
    }

    public String getTypeParameter() {
        return this.typeParameter;
    }

    public AuthenticationTokenProducer getTokenProducer() {
        return tokenProducer;
    }

    public void setTokenProducer(AuthenticationTokenProducer tokenProducer) {
        this.tokenProducer = tokenProducer;
    }

    public ISecurityEventHook getSecurityEventHook() {
        return securityEventHook;
    }

    public void setSecurityEventHook(ISecurityEventHook securityEventHook) {
        this.securityEventHook = securityEventHook;
    }

    public void addTokenFactory(IAuthenticationTokenFactory factory) {
        this.tokenProducer.addAuthenticationTokenFactory(factory);
    }
}
